﻿using Pathfinding;
using UnityEngine;
using UnityEngine.Events;

public class BirdUnit : MonoBehaviour {

	public Transform target;
	public float speed;
	public float nextWayPointDistance = 3;

	Path path;
	int currentWaypoint = 0;
	bool reachedEndOfPath;

	Seeker seeker;
	Rigidbody2D rb;


	Vector2 ve = Vector3.zero;
	[System.Serializable]
	public class FlipEvent : UnityEvent<float> { }
	[SerializeField] FlipEvent flipEvent;

	public bool StartFinding {
		get;
		set;
	}

	private void Awake() {

		seeker = GetComponent<Seeker>();
		rb = GetComponent<Rigidbody2D>();
		InvokeRepeating("UpdatePath", 0f, .5f);

		if (flipEvent == null)
			flipEvent = new FlipEvent();

	}

	private void Start() {
	}

	void UpdatePath() {
		if(seeker.IsDone())
			seeker.StartPath(rb.position, target.position, OnPathCompete);
	}

	public void FllowBoy(Transform target) {
		if (!target.Equals(this.target)) {
			seeker.StartPath(rb.position, target.position, OnPathCompete);
			this.target = target;
		}

		if (path == null)
			return;
		if (currentWaypoint >= path.vectorPath.Count) {
			reachedEndOfPath = true;
			return;
		} else {
			reachedEndOfPath = false;
			StartFinding = false;
		}

		Vector2 direction = ((Vector2)path.vectorPath[currentWaypoint] - rb.position).normalized;

		rb.velocity = direction * speed * Time.deltaTime;
		flipEvent.Invoke(rb.velocity.normalized.x);
		float distance = Vector2.Distance(rb.position, path.vectorPath[currentWaypoint]);

		if (distance < nextWayPointDistance) {
			currentWaypoint++;
		}
	}

	void OnPathCompete(Path p) {
		if (!p.error) {
			path = p;
			currentWaypoint = 0;
		}
	}

	void Flip() {
		transform.localScale = new Vector3(transform.position.x - target.position.x > 0 ? -1 : 1, 1f, 0);
	}

}
